package com.qbccn.onlinetest.config.custom;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linke
 * @date 2020/5/23 18:18
 * @description 用户登录失败时返回给前端的数据
 */
@Component
public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
  @Override
  public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", 1);
    if (e instanceof UsernameNotFoundException) {
      jsonObject.put("message", "账号不存在");
    } else if (e instanceof BadCredentialsException) {
      System.out.println(e.getMessage());
      jsonObject.put("message", "密码错误");
    } else if (e instanceof RuntimeException) {
      jsonObject.put("message", e.getMessage());
    } else {
      jsonObject.put("message", "未知错误");
    }
    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
    httpServletResponse.getWriter().write(jsonObject.toJSONString());
  }
}
